import { Component, OnInit, ViewChild, TemplateRef, ElementRef, ViewContainerRef, EmbeddedViewRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-tpl-container',
  templateUrl: './tpl-container.component.html'
})
export class TplContainerComponent implements OnInit, AfterViewInit {
  private freeViewRef: EmbeddedViewRef<any>;
  // @ViewChild获取模板元素（component/ng-template/dom）
  @ViewChild('boxEle', { static: true }) readonly boxEl: ElementRef;
  @ViewChild('firstTpl', { read: TemplateRef, static: true }) readonly firstTpl: TemplateRef<any>;
  @ViewChild('secondTpl', { read: TemplateRef, static: true }) readonly secondTpl: TemplateRef<any>;
  @ViewChild('thirdTpl', { read: TemplateRef, static: true }) readonly thirdTpl: TemplateRef<any>;
  @ViewChild('fourthTpl', { read: TemplateRef, static: true }) readonly fourthTpl: TemplateRef<any>;
  @ViewChild('freeTpl', { read: TemplateRef, static: true }) readonly freeTpl: TemplateRef<any>;
  @ViewChild('firstContainer', { read: ViewContainerRef, static: true }) readonly firstContain: ViewContainerRef;
  @ViewChild('secondContainer', { read: ViewContainerRef, static: true }) readonly secondContain: ViewContainerRef;
  constructor() { }

  ngOnInit() {
  }
  ngAfterViewInit(): void {
    const viewTpl = this.firstTpl.createEmbeddedView(null);
    this.boxEl.nativeElement.appendChild(viewTpl.rootNodes[0]);
    this.boxEl.nativeElement.appendChild(viewTpl.rootNodes[1]);
    // freeViewRef只会被创建一次
    this.freeViewRef = this.freeTpl.createEmbeddedView({ $implicit: 'default', free: 'abc' });
    setTimeout(() => {
      this.firstContain.createEmbeddedView(this.firstTpl);
    }, 0);
  }
  insert(tpl: TemplateRef<any>): void {
    this.firstContain.insert(tpl.createEmbeddedView(null));
  }
  insertFree(): void {
    this.firstContain.insert(this.freeViewRef, 0);
  }
  insertAll(): void {
    [this.firstTpl, this.secondTpl, this.thirdTpl, this.fourthTpl, this.freeTpl].forEach((item) => {
      this.firstContain.insert(item.createEmbeddedView({ $implicit: 'default', free: 'abc' }));
    });
  }
  getOne(): void {
    console.log(this.firstContain.get(2));
    console.log(this.firstContain.indexOf(this.freeViewRef));
  }
  moveFree(): void {
    this.firstContain.move(this.freeViewRef, 2);
  }
  exchange(): void {
    const view = this.firstContain.detach(1);
    this.firstContain.insert(view, 3);
  }
  moveToOuter(): void {
    const view = this.firstContain.detach(2);
    this.secondContain.insert(view);
  }
}
